package za.org.jcicada.confss.impl;

import java.lang.management.ManagementFactory;

import com.sun.management.OperatingSystemMXBean;

/**
 * http://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information
 */
public class PerformanceMonitor {

	private int availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();
	private long lastSystemTime = 0;
	private long lastProcessCpuTime = 0;

	public synchronized double getCpuUsage() {
		if (lastSystemTime == 0) {
			baselineCounters();
			return 0;
		}

		long systemTime = System.nanoTime();
		long processCpuTime = 0;

		if (getOperatingSystemMXBean() instanceof OperatingSystemMXBean) {
			processCpuTime = ((OperatingSystemMXBean) getOperatingSystemMXBean()).getProcessCpuTime();
		}

		double cpuUsage = (double) (processCpuTime - lastProcessCpuTime) / (systemTime - lastSystemTime);

		lastSystemTime = systemTime;
		lastProcessCpuTime = processCpuTime;

		return cpuUsage / availableProcessors;
	}

	private void baselineCounters() {
		lastSystemTime = System.nanoTime();

		if (getOperatingSystemMXBean() instanceof OperatingSystemMXBean) {
			lastProcessCpuTime = ((OperatingSystemMXBean) getOperatingSystemMXBean()).getProcessCpuTime();
		}
	}
	
	private java.lang.management.OperatingSystemMXBean getOperatingSystemMXBean() {
		return ManagementFactory.getOperatingSystemMXBean();
	}
}
